import request, { API_TOKEN_STORAGE_KEY } from './api/request'

// 在此处定义路由页面
const routeView = {
  'account': () => import('./pages/account/index.vue'),
  'account/save': () => import('./pages/account/save.vue'),
  'role': () => import('./pages/role/index.vue'),
  'role/save': () => import('./pages/role/save.vue'),
  'member': () => import('./pages/member/index.vue'),
  'bannerImage': () => import('./pages/banner/index.vue'),
  'bannerImage/save': () => import('./pages/banner/save.vue'),
}

export default async function(router, route, store) {
  const token = localStorage.getItem(API_TOKEN_STORAGE_KEY)
  if (!token) {
    router.replace('/login')
    throw { code: 10001, msg: '请先登录' }
  }
  const res = await request({
    method: 'get',
    url: 'admin/user/profile',
  })
  store.commit('username', res.nickname ? res.nickname : res.username)
  store.commit('menus', res.role.menus)

  let isJump = false
  for (const i in res.role.menus) {
    const m = res.role.menus[i]
    if (router.getRoutes().find(r => r.path == `/home/${m.path}`)) continue
    if (!Object.prototype.hasOwnProperty.call(routeView, m.path)) continue
    router.addRoute('main', {
      component: routeView[m.path],
      path: m.path,
      name: m.name,
      meta: {
        group: m.group,
        icon: m.icon
      }
    })
    // console.log(route.path.split('/').length)
    if (!isJump && route.path.split('/').length < 3) {
      router.replace(`/home/${m.path}`)
      isJump = true
    }
  }
  console.log(router.getRoutes())
  router.addRoute({
    path: '/:pathMatch(.*)*',
    name: 'notfound',
    component: () => import('./components/notfound.vue')
  })
  if (!isJump) router.replace(route.fullPath)
  return res
}